package com.qimei.onerice.servlet;

import com.qimei.onerice.entity.Admin;
import com.qimei.onerice.entity.Customer;
import com.qimei.onerice.entity.Order;
import com.qimei.onerice.service.AdminService;
import com.qimei.onerice.service.CustomerService;
import com.qimei.onerice.service.impl.AdminServiceImpl;
import com.qimei.onerice.service.impl.CustomerServiceImpl;
import com.qimei.onerice.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String identity = request.getParameter("identity");
			String username = request.getParameter("username");
			String password = request.getParameter("password");

			System.out.println(identity);
			System.out.println(username);
			System.out.println(password);

			switch (identity) {
				case "admin":
					AdminService adminService = new AdminServiceImpl();
					Admin authenticatedAdmin = adminService.adminLogin(username, password);
					request.getSession().setAttribute("user", authenticatedAdmin);
					request.getRequestDispatcher("/view/manage/adminManage.jsp").forward(request, response);
					break;
				case "customer":
					CustomerService customerService = new CustomerServiceImpl();
					Customer authenticatedCustomer = customerService.customerLogin(username, password);
					Order currentOrder = new OrderServiceImpl().getCurrentOrder();
					request.getSession().setAttribute("order", currentOrder);
					handleLoginResponse(authenticatedCustomer, request, response);
					break;
				default:
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write("{\"error\": \"未选择身份\"}");
					break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "请求错误");
		}
	}

	private void handleLoginResponse(Object user, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if (user != null) {
			// 登录成功
			request.getSession().setAttribute("user", user);

			response.sendRedirect(request.getContextPath() + "/view/home.jsp");

		} else {
			// 登录失败
			String errorMessage = "账号或密码错误";
			request.setAttribute("errorMessage", errorMessage);

			// 转发回登录页面
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}
}